import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Logger } from '../common/logger/logger';

// 参考 https://tuture.co/2020/05/12/@uXOOfFmhS/
@Injectable()
export class TransformInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const req = context.getArgByIndex(1).req;

    return next.handle().pipe(
      map((data) => {
        const logFormat = JSON.stringify({
          ip: req.ip,
          user: `${req.user}`,
          resUrl: req.originalUrl,
          resMethod: req.method,
          data: data,
        });
        Logger.info(logFormat);
        Logger.access(logFormat);
        return data;
      }),
    );
  }
}
